package com.jsgt.greekfire.ui.wallet.add

import android.app.Activity
import android.content.Intent
import android.text.Selection
import android.text.Spannable
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.StringUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.PASSWORD_MIN_LENGTH
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.YTWallet
import com.jsgt.greekfire.common.util.YTWalletUtils
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.dao.model.WalletBean
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import com.jsgt.greekfire.ui.me.backup.BackupActivity
import kotlinx.android.synthetic.main.activity_create_wallet.*

class CreateWalletActivity : BaseActivity(), View.OnClickListener {
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }
    private var coin: String? = null

    private var wallet: YTWallet? = null
    private var identityBean: IdentityBean? = null

    private var launcher: ActivityResultLauncher<Intent>? = null

    override fun needFitsSystemWindows(): Boolean {
        return false
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_create_wallet
    }

    override fun main() {
        setStatusBar(R.color.transparent, false, R.color.white)
        coin = intent.getStringExtra("coin")
        if (coin.isNullOrEmpty()) {
            finish()
        }
        title = String.format(getString(R.string.create_wallet_title), coin)
        txvOk.setOnClickListener(this)

        cbPassword.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                edtPassword.transformationMethod =
                    HideReturnsTransformationMethod.getInstance()
            } else {
                edtPassword.transformationMethod =
                    PasswordTransformationMethod.getInstance()
            }
            endSelection(edtPassword)
        }
        cbPasswordRepeat.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                edtPasswordRepeat.transformationMethod =
                    HideReturnsTransformationMethod.getInstance()
            } else {
                edtPasswordRepeat.transformationMethod =
                    PasswordTransformationMethod.getInstance()
            }
            endSelection(edtPasswordRepeat)
        }

        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                walletViewModel.addIdentity(identityBean!!)

            }else{
                showProgress(false)
                txvOk.isEnabled = true
            }
        }

        walletViewModel.getAllIdentity()?.observe(this, Observer { it1 ->
            if (it1.isNotEmpty() && wallet != null) {
                it1.forEach { it2 ->
                    if (it2.getPriKeyByAES() == wallet!!.getEcKeyPair().privateKey.toString()) {
                        val walletBean = WalletBean()
                        walletBean.key = "ATR"
                        walletBean.identityId = it2.id
                        walletBean.address = wallet!!.address
                        walletBean.name = edtContent.text.toString().trim()
                        walletBean.selection = 0
                        walletViewModel.addWallet(walletBean)
                        return@forEach
                    }
                }
            }
        })
        walletViewModel.getAllWallet()?.observe(this, Observer { it1 ->
            if (it1 != null && wallet != null) {
                it1.forEach { it2 ->
                    if (it2.address == wallet!!.address) {
                        setResult(Activity.RESULT_OK)
                        finish()
                        return@forEach
                    }
                }
            }
            showProgress(false)
            txvOk.isEnabled = true
        })
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.txvOk -> {
                showProgress(true)
                txvOk.isEnabled = false
                if (!checkContent()) {
                    txvOk.isEnabled = true
                    showProgress(false)
                    return
                } else if (edtPassword.text.isNullOrEmpty()) {
                    ToastUtils.show(R.string.please_input_password)
                    txvOk.isEnabled = true
                    showProgress(false)
                    return
                } else if (edtPasswordRepeat.text.isNullOrEmpty()) {
                    ToastUtils.show(R.string.please_input_password_repeat)
                    txvOk.isEnabled = true
                    showProgress(false)
                    return
                } else if (!TextUtils.equals(edtPassword.text, edtPasswordRepeat.text)) {
                    ToastUtils.show(R.string.wallet_pwd_warning)
                    txvOk.isEnabled = true
                    showProgress(false)
                    return
                } else if (edtPassword.text!!.toString().trim().length < PASSWORD_MIN_LENGTH) {
                    ToastUtils.show(this, getString(R.string.wallet_safe_pwd_warning))
                    txvOk.isEnabled = true
                    showProgress(false)
                    return
                } else {
                    identityBean = IdentityBean()
                    identityBean!!.backup = true
                    identityBean!!.setPasswordByMd5(edtPassword.text!!.toString().trim())
                    if (edtPasswordTips.text.isNotEmpty()) {
                        identityBean!!.passwordTips = edtPasswordTips.text.toString()
                    }

                    wallet =
                        YTWalletUtils.generateBip44Wallet(
                            YTWalletUtils.getMnemonic(),
                            identityBean!!.password
                        )
                    if (wallet != null) {
                        identityBean!!.setMnemonicByAES(wallet!!.getMnemonic())
                        identityBean!!.setPriKeyByAES(wallet!!.getEcKeyPair().privateKey.toString())

                        launcher?.launch(
                            Intent(
                                this,
                                BackupActivity::class.java
                            ).putExtra("identity", identityBean)
                        )
                    } else {
                        txvOk.isEnabled = true
                        showProgress(false)
                    }
                }
            }
        }
    }

    fun checkContent(): Boolean {
        if (edtContent.text.isNullOrEmpty()) {
            ToastUtils.show(R.string.please_input_wallet_name)
            return false
        }
        return true
    }

    /**
     * 设置EditText游标至末尾
     */
    private fun endSelection(editText: EditText) {
        val text: Spannable? = editText.text
        if (text != null) {
            Selection.setSelection(text, text.length)
        }
    }
}